<%= stylesheet_link_tag("ajaxtree.css") %>

<div id="mytree" class="mytree">
  <% ancestors = focus_category.ancestors.collect{|parent| parent.id} if focus_category.parent %>
  <%= get_tree_data(all_categories, root_category_id, ancestors) {|n|
      link_to_remote(n.name,
        :url      => {:controller => 'categories', :action => 'display_clicked_item', :id => n.id},
        :loading  => "Element.show('tree_indicator'); toggleBackground($('#{n.id}_tree_item'));",
        :complete => "Element.hide('tree_indicator')"
    )} %>

  <% all_categories.each do |node| %>
    <%= draggable_element node.id.to_s+'_tree_div', :revert => true, :snap => false, :handle => "'#{node.id.to_s}_drag_image'" %>
    <%= drop_receiving_element node.id.to_s+'_tree_div',
        :accept   => 'inner_tree_element',
        :url      => {:controller => 'categories', :action => 'sort_ajax_tree', :parent_id => node.id, :id => nil},
        :loading  => "Element.show('sort_tree_indicator')",
        :complete => "Element.hide('sort_tree_indicator')"
    %>
  <% end %>

  <%= image_tag 'indicator.gif', :id => 'tree_indicator',      :style => 'display:none' %>
  <%= image_tag 'indicator.gif', :id => 'sort_tree_indicator', :style => 'display:none' %>
</div>

<script type="text/javascript">

  var selected_el = document.getElementById('<%= focus_category.id %>_tree_item');
  selected_el.className='highlighted';

  function toggleMyTree(id)
  {
    Element.toggle(id+'collapsed');
    Element.toggle(id+'expanded');
    Element.toggle(id+'children');
    return false;
  }
  function toggleBackground(el)
  {
    // using collection proxies to change the background
    var highlighted_el = $$("span.highlighted");
    highlighted_el.all(function(value,index){return value.className='normal'});
  
    el.className='highlighted';
    selected_el = el;
    return false;
  }
  function openMyTree(id)
  {
    Element.hide(id+'collapsed');
    Element.show(id+'expanded');
    Element.show(id+'children');
    return false;
  }
  
  function toggleDiv()
  {
    Element.toggle('mytree');
    Element.toggle('expanded');
    Element.toggle('collapsed');
    return false;
  }
  function showDrag()
  {
    var drag_images = $$('img.drag_image');
    drag_images.all(function(value,index){return value.style.display='inline';});
    Element.toggle('done');
    Element.toggle('reorder');
    return false;
  }
  function hideDrag()
  {
    var drag_images = $$('img.drag_image');
    drag_images.all(function(value,index){return value.style.display='none';});
    Element.toggle('done');
    Element.toggle('reorder');
    return false;
  }
</script>
